//
//  LoginViewController.m
//  FaesFarma_iPad
//
//  Created by Jose on 04/07/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "LoginViewController.h"
#import "RootViewController.h"
#import "DetailViewController.h"

#define TEXTFIELD_MOVEMENT_DISTANCE 165
#define TEXTFIELD_MOVEMENT_DURATION 0.3f

@interface  LoginViewController ()


- (void) animateView: (int) distance;

//- (NSData *) makeAuthQuery: (NSString *) username andPassword: (NSString *) password;
//- (void) doSendQuery: (NSData *) data toService: (NSString *) url;

- (void) doLoginError: (NSString *) message;
    



- (void)registerForKeyboardNotifications;
- (void)keyboardWasShown:(NSNotification*)aNotification;
- (void)keyboardWillBeHidden:(NSNotification*)aNotification;
- (void) launchMenu;

@property (nonatomic, retain) NSMutableData * receivedData;



@end

@implementation LoginViewController

@synthesize usernameField, passwordField;
@synthesize receivedData;
@synthesize authURL;
@synthesize appDelegate;

#pragma mark - 
#pragma mark View lifecycle

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Inicialización
        self.receivedData = [[[NSMutableData alloc] initWithCapacity:5000] autorelease];
        
        firstTime = YES;
        [self registerForKeyboardNotifications];
    }
    return self;
}

- (void)dealloc
{
    [usernameField release];
    [passwordField release];
    [receivedData release];
    [authURL release];
    [activityAlert release];
    
    [appDelegate release];
    
    [super dealloc];
}

- (void) viewDidLoad{
    [super viewDidLoad];
    
    usernameField.delegate = self;
    passwordField.delegate = self;
}


- (void) viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    
    
    
}


- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return UIInterfaceOrientationIsLandscape(interfaceOrientation);
}



#pragma mark - 
#pragma mark Action Methods

- (IBAction) doCheckLogin: (id) sender 
{
    [self launchMenu];
}  


- (BOOL)textFieldShouldReturn:(UITextField *)aTextField 
{
    if ([usernameField.text length] == 0 || [passwordField.text length] == 0)
        return NO;
    
    [aTextField resignFirstResponder];
    [self doCheckLogin: nil];
    return NO;
}

- (void) textFieldDoneEditing: (id) sender 
{
    [sender resignFirstResponder];
}

- (IBAction) backgroundTap: (id)sender 
{
    [self.usernameField resignFirstResponder];
    [self.passwordField resignFirstResponder];
}

- (void) animateView: (int) distance
{
    [UIView beginAnimations: @"TEXTFIELD_ANIM" context: nil];
    [UIView setAnimationBeginsFromCurrentState: YES];
    [UIView setAnimationDuration: TEXTFIELD_MOVEMENT_DURATION];
    self.view.frame = CGRectMake(distance, 0, self.view.frame.size.width, self.view.frame.size.height);
    [UIView commitAnimations];
}


- (void)registerForKeyboardNotifications
{
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWasShown:)
                                                 name:UIKeyboardWillShowNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillBeHidden:)
                                                 name:UIKeyboardWillHideNotification object:nil];
}

- (void)keyboardWasShown:(NSNotification*)aNotification
{
    UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];
    if (orientation == UIInterfaceOrientationLandscapeRight) {
        [self animateView: TEXTFIELD_MOVEMENT_DISTANCE];
    } else {
        [self animateView: -TEXTFIELD_MOVEMENT_DISTANCE];
    }
}

- (void)keyboardWillBeHidden:(NSNotification*)aNotification
{
    UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];
    if (orientation == UIInterfaceOrientationLandscapeRight) {
        [self animateView: 0];
    } else {
        [self animateView: 20];
    }
  
}
     
#pragma mark - 
#pragma mark Private Methods

- (void) launchMenu{
   
    [self.appDelegate loginOk];
}

- (void) doLoginError: (NSString *) message 
{
    UIAlertView * alertView = [[UIAlertView alloc] initWithTitle: NSLocalizedString(@"ERROR",nil)
                                                         message: message
                                                        delegate: nil 
                                               cancelButtonTitle: NSLocalizedString(@"Aceptar",nil) 
                                               otherButtonTitles: nil];
    [alertView show];
    [alertView release];
}

#pragma mark - 
#pragma mark Connection Delegate Methods

- (void) connection: (NSURLConnection *) connection didReceiveResponse: (NSURLResponse *) response
{
    [self.receivedData setLength:0];
}


- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)moreData
{
    if (self.receivedData == nil)
		return;
	
	[self.receivedData appendData:moreData];

}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{ 
    [self stopIndicator];
    
    [self doLoginError: @"Error al conectar"];
}


- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
    [self stopIndicator];
    
    //Compruebo los datos
}



//##########
//INDICATORS
//##########
- (void) stopIndicator{
	[activityAlert close];
}

- (void) startIndicatorWithMessage: (NSString *) message{
	if (activityAlert==nil){
		activityAlert = [[ActivityAlertView alloc] 
						 initWithTitle:@""
						 message:@""
						 delegate:self cancelButtonTitle:nil 
						 otherButtonTitles:nil];
	}
	
	activityAlert.message = message;
	
	
    [activityAlert showAfter: 0.5];
	
}

- (void) changeIndicatorMessage: (NSString *) message{
    activityAlert.message = message;
}

- (void) startIndicator{
	[self startIndicatorWithMessage:@""];
	
}


@end
